<template>
	<div class="app-container" v-loading="loading">
		<div class="search-container app_ny">
			<div class="div2" style="position: relative">
				<el-row :gutter="12" style="width: 100%">
					<el-col :span="4">
						<el-tree-select placeholder="请选择部门"
							:expand-on-click-node="false"
							:check-on-click-node="true"
							check-strictly
							v-model="queryParams.department" clearable
							:data="baseConfigStore.newExDepartmentList" 
							:props="{
							  label: 'name',
							  children: 'children',
							  value: 'id',
							}">
							<template v-slot:default="{ node,data }">
								<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
							</template>
						</el-tree-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.name" clearable placeholder="请输入姓名" @keyup.enter="handleQuery" />
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.position" clearable placeholder="请输入职务" />
					</el-col>
					
					
					<el-col :span="14">
						<el-button :loading="loading" type="primary" @click="handleQuery"><template
								#icon><i-ep-search /></template>查询</el-button>
								<el-button v-hasPerm="['UserExport']" type="primary" @click="onExport()"><template
										#icon><i-ep-download /></template>导出</el-button>
						<el-dropdown split-button v-hasPerm="['UserImport']" style="margin-left: 12px;">
							导入
							<template #dropdown>
								<el-dropdown-menu>
									<el-dropdown-item @click="downloadTemplate"><i-ep-download />下载模板</el-dropdown-item>
									<el-dropdown-item @click="openImportDialog"><i-ep-top />导入数据</el-dropdown-item>
								</el-dropdown-menu>
							</template>
						</el-dropdown>
					</el-col>
				</el-row>
				<FilterColumn class="filtBox" @handleRefresh="resetQuery()" @handleLaunch="filterMore()" :launch="true"
					:showMore="showMore" :strtype="strtype"></FilterColumn>
			</div>
			<div v-if="showMore" class="index_header_input">
				<el-row :gutter="12" style="width:100%">
					<el-col :span="3">
						<el-input v-model="queryParams.seniority" clearable placeholder="请输入工龄" />
					</el-col>
					<el-col :span="3">
						<el-tree-select v-model="queryParams.roles" clearable :default-expand-all="true"
							placeholder="请选择角色" :data="roleOptions" :props="{
										  label: 'role_name',
										  children: 'children',
										  value: 'id',
										}" filterable check-strictly :render-after-expand="false" />
					</el-col>
					<el-col :span="3">
						<el-select v-model="queryParams.type" clearable placeholder="请选择人员性质">
							<el-option label="合同工" :value="1" />
							<el-option label="派遣工" :value="2" />
							<el-option label="外包" :value="3" />
						</el-select>
					</el-col>

					<el-col :span="3">
						<el-select v-model="queryParams.gender" clearable placeholder="请选择性别">
							<el-option label="男" :value="1" />
							<el-option label="女" :value="2" />
						</el-select>
					</el-col>

					<el-col :span="3">
						<el-select v-model="queryParams.xueli" clearable placeholder="请选择学历">
							<el-option label="全日制" :value="1" />
							<el-option label="非全日制" :value="2" />
							<el-option label="本科" :value="3" />
							<el-option label="专科" :value="4" />
							<el-option label="其他" :value="0" />
						</el-select>
					</el-col>
					<el-col :span="3">
						<el-select v-model="queryParams.zhicheng" clearable placeholder="请选择职称">
							<el-option label="初级" :value="1" />
							<el-option label="中级" :value="2" />
							<el-option label="高级" :value="3" />
						</el-select>
					</el-col>
					<el-col :span="3">
						<el-input v-model="queryParams.zhengshu" clearable placeholder="请输入证书" />
					</el-col>
				</el-row>
			</div>
			<div v-if="showMore" class="index_header_input">
				<el-row :gutter="12" style="width:100%">
					<el-col :span="6">
						<el-date-picker style="width: 100%;" start-placeholder="参加工作时间" end-placeholder="参加工作时间"
							v-model="queryParams.work_time" clearable value-format="YYYY-MM-DD" type="daterange" />
					</el-col>
					<el-col :span="6">
						<el-date-picker style="width: 100%;" start-placeholder="职务任命时间" end-placeholder="职务任命时间"
							v-model="queryParams.renming_time" clearable value-format="YYYY-MM-DD" type="daterange" />
					</el-col>
					<el-col :span="6">
						<el-date-picker style="width: 100%;" start-placeholder="入党时间" end-placeholder="入党时间"
							v-model="queryParams.join_time" clearable value-format="YYYY-MM-DD" type="daterange" />
					</el-col>
					<el-col :span="6">
						<el-date-picker style="width: 100%;" v-model="queryParams.contract_date"
							start-placeholder="合同签订日期" end-placeholder="合同签订日期" clearable value-format="YYYY-MM-DD"
							type="daterange" />
					</el-col>


				</el-row>
			</div>
		</div>

		<el-card shadow="never">
			
			<div class="action-row">
				<el-button v-hasPerm="['User/save']"   @click="handleDo('','act_add')" type="primary" plain><template #icon><i-ep-plus /></template>新增</el-button>
				<el-button v-hasPerm="['User/update']" @click="handleDo('', 'act_edit')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-edit/></template>修改</el-button>
				<el-button v-hasPerm="['User/delete']" @click="handleDo('', 'act_del')" :disabled="multipleSelection.length !== 1" :type="buttonType(multipleSelection.length)" plain><template #icon><i-ep-delete/></template>删除</el-button>
			</div>
			<el-table ref="dataTableRef" 
				v-loading="loading" 
				:data="tableData"
				align="left" 
				border
				tooltip-effect="dark"
				:show-overflow-tooltip="true"
				:scrollbar-always-on="true"
				@cell-mouse-enter="rowMouse"
				@cell-mouse-leave="menuLineVisible=false"
				@selection-change="handleSelectionChange">
				<el-table-column type="selection" align="center" width="55" />
				<template v-for="(item,index) in cColumnsList()" :key='index'>
					<el-table-column :label="item.label" :align="item.align" :prop="item.prop" :width="item.width" :min-width="item.minwidth">
						<template v-if="item.prop == 'gender'" #default="scope">
							<el-text v-if="scope.row.gender == 1">男</el-text>
							<el-text v-else>女</el-text>
						</template>
						<template v-if="item.prop == 'type'" #default="scope">
							<el-text v-if="scope.row.type == 1">合同工</el-text>
							<el-text v-if="scope.row.type == 2">派遣工</el-text>
							<el-text v-if="scope.row.type == 3">外包</el-text>
						</template>
						<template v-if="item.prop == 'contract.status'" #default="scope">
							<el-text v-if="scope.row.contract.status == 1"
								type="success">{{ scope.row.contract.end_time }}</el-text>
							<el-text v-if="scope.row.contract.status == 2"
								type="warning">{{ scope.row.contract.end_time }}</el-text>
							<el-text v-if="scope.row.contract.status == 3"
								type="danger">{{ scope.row.contract.end_time }}(已到期)</el-text>
						</template>
						<template v-if="item.prop == 'department_name'" #default="scope">
							{{ scope.row.department_name }}
						</template>
						<template v-if="item.prop == 'seniority'" #default="scope">
							{{ scope.row.seniority }} 年
						</template>
					</el-table-column>
				</template>
			</el-table>
			<pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page"
				v-model:limit="queryParams.limit" @pagination="handleQuery" />
		</el-card>

		<!-- 表单弹窗 -->
		<el-dialog v-model="dialogAdd.visible"   :title="dialogAdd.title" width="1000" @close="closeDialog">
			<el-form ref="dataFormRef" :model="formData" :rules="rules" v-loading="loadingAdd" label-width="100px">
				<el-tabs v-model="activeName" class="demo-tabs">
					<el-tab-pane label="基本信息" name="user">
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="部门" prop="department">
									<el-tree-select ref="departmentRef" v-model="formData.department" placeholder="请选择部门"
										:data="baseConfigStore.newExDepartmentList" filterable check-strictly
										:render-after-expand="false" multiple show-checkbox check-on-click-node>
										<template v-slot:default="{node, data }">
											<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
										</template>
									</el-tree-select>
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="角色" prop="roles">
									<el-tree-select v-model="formData.roles" :default-expand-all="true"
										placeholder="请选择角色" :data="roleOptions" :props="{
										  label: 'role_name',
										  children: 'children',
										  value: 'id',
										}" filterable check-strictly :render-after-expand="false" multiple check-on-click-node />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="姓名" prop="name">
									<el-input v-model="formData.name" placeholder="请输入姓名" />
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="职务" prop="position">
									<el-input v-model="formData.position" placeholder="请输入职务" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="人员性质" prop="type">
									<el-select v-model="formData.type" placeholder="请选择人员性质">
										<el-option label="合同工" :value="1" />
										<el-option label="派遣工" :value="2" />
										<el-option label="外包" :value="3" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="性别" prop="gender"  >
									<el-select v-model="formData.gender" placeholder="请选择性别">
										<el-option label="男" :value="1" />
										<el-option label="女" :value="2" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="联系方式" prop="mobile">
									<el-input v-model="formData.mobile" placeholder="请输入联系方式" />
								</el-form-item>
							</el-col>

							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="身份证号" prop="idcard">
									<el-input v-model="formData.idcard" placeholder="请输入身份证号" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="民族" prop="nation">
									<el-input v-model="formData.nation" placeholder="请输入民族" />
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="籍贯" prop="native_place">
									<el-input v-model="formData.native_place" placeholder="请输入籍贯" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="出生年月" prop="birthday">
									<el-date-picker v-model="formData.birthday" placeholder="请输入出生年月"
										style="width: 100%;" value-format="YYYY-MM-DD" type="date" />
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="参加工作时间" prop="work_time">
									<el-date-picker v-model="formData.work_time" placeholder="请输入参加工作时间"
										style="width: 100%;" value-format="YYYY-MM-DD" type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="政治面貌" prop="political_landscape">
									<el-select v-model="formData.political_landscape" placeholder="请选择政治面貌">
										<el-option label="群众" :value="0" />
										<el-option label="预备党员" :value="1" />
										<el-option label="党员" :value="2" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="入党时间" prop="join_time">
									<el-date-picker v-model="formData.join_time" placeholder="请输入入党时间"
										style="width: 100%;" value-format="YYYY-MM-DD" type="date" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="职务任命时间" prop="renming_time">
									<el-date-picker v-model="formData.renming_time" placeholder="请输入职务任命时间"
										style="width: 100%;" value-format="YYYY-MM-DD" type="date" />
								</el-form-item>
							</el-col>
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="工龄(年)" prop="seniority" >
									<el-input v-model="formData.seniority" placeholder="请输入工龄(年)" />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="10">
							<el-col :xs="11" :sm="11" :md="11">
								<el-form-item label="是否有招工手续审批表" prop="is_zhaogong" :label-width="170">
									<el-select v-model="formData.is_zhaogong" placeholder="请选择是否有招工手续审批表">
										<el-option label="否" :value="0" />
										<el-option label="是" :value="1" />
									</el-select>
								
								</el-form-item>
							</el-col>
						</el-row>
						<el-form-item label="照片" prop="avatar">
							<single-upload v-model="formData.avatar" />
						</el-form-item>
						<el-form-item label="备注" prop="mark">
							<el-input type="textarea"  v-model="formData.mark" placeholder="请输入备注信息" rows="5" resize="none" show-word-limit maxlength="200" />
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="人员调动记录" name="transfer">
						<el-table :data="transferData" style="width: 100%">
							<el-table-column label="调动类型" align="center">
								<template #default="scope">
									<el-select class="defalut-width" v-model="scope.row.type" placeholder="请选择级别">
										<el-option label="入职" :value="1" />
										<el-option label="借入" :value="2" />
										<el-option label="转岗" :value="3" />
										<el-option label="借调" :value="4" />
										<el-option label="离职" :value="5" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column label="调动日期" align="center">
								<template #default="scope">
									<el-date-picker v-model="scope.row.date" type="date" placeholder="请选择调动日期"
										format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
								</template>
							</el-table-column>
							<el-table-column label="调动部门" align="center">
								<template #default="scope">
									<el-input type="text" v-if="scope.row.type"
										:placeholder="`请输入${retunTypeA(scope.row.type)}部门`" v-model="scope.row.place" />
								</template>
							</el-table-column>
							<el-table-column label="操作" align="center" width="150">
								<template #default="scope">
									<el-button type="danger" size="small" link
										@click="handleTransferDataDelete(scope.$index)">
										<template #icon><i-ep-delete /></template>删除
									</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-row>
							<el-button type="primary" @click="handleTransferDataAdd">添加记录</el-button>
						</el-row>
					</el-tab-pane>
					<el-tab-pane label="学历" name="xueli">
						<h3>全日制学历</h3>
						<el-form-item  label="学历及学位" prop="qrzData.xueli">
							<el-select class="defalut-width" v-model="formData.qrzData.xueli" placeholder="请选择学历及学位">
								<el-option label="全日制" value="1" />
								<el-option label="非全日制" value="2" />
								<el-option label="本科" value="3" />
								<el-option label="专科" value="4" />
								<el-option label="其他" value="0" />
							</el-select>

						</el-form-item>
						<el-form-item  label="毕业院校" prop="qrzData.school">
							<el-input v-model="formData.qrzData.school" placeholder="请输入毕业院校" />
						</el-form-item>
						<el-form-item  label="专业" prop="qrzData.zhuanye">
							<el-input v-model="formData.qrzData.zhuanye" placeholder="请输入专业" />
						</el-form-item>
						<h3>最高学历</h3>
						<el-form-item  label="学历及学位" prop="zgxlData.xueli">
							<el-select class="defalut-width" v-model="formData.zgxlData.xueli" placeholder="请选择学历及学位">
								<el-option label="全日制" value="1" />
								<el-option label="非全日制" value="2" />
								<el-option label="本科" value="3" />
								<el-option label="专科" value="4" />
								<el-option label="其他" value="0" />
							</el-select>
						</el-form-item>
						<el-form-item  label="毕业院校" prop="zgxlData.school">
							<el-input v-model="formData.zgxlData.school" placeholder="请输入毕业院校" />
						</el-form-item>
						<el-form-item  label="专业" prop="zgxlData.zhuanye">
							<el-input v-model="formData.zgxlData.zhuanye" placeholder="请输入专业" />
						</el-form-item>
					</el-tab-pane>
					<el-tab-pane label="职称/证书" name="zhicheng">
						<el-table :data="zhichengData" style="width: 100%">
							<el-table-column label="级别" align="center">
								<template #default="scope">
									<el-select class="defalut-width" v-model="scope.row.jibie" placeholder="请选择级别">
										<el-option label="初级" value="1" />
										<el-option label="中级" value="2" />
										<el-option label="高级" value="3" />
									</el-select>
								</template>
							</el-table-column>
							<el-table-column label="专业" align="center">
								<template #default="scope">
									<el-input v-model="scope.row.zhuanye" placeholder="请输入专业" />
								</template>
							</el-table-column>
							<el-table-column label="技能证书" align="center">
								<template #default="scope">
									<el-input v-model="scope.row.zhengshu" placeholder="请输入技能证书" />
								</template>
							</el-table-column>
							<el-table-column label="操作" align="center" width="150">
								<template #default="scope">
									<el-button type="danger" size="small" link
										@click="handleZhichengDelete(scope.$index)">
										<template #icon><i-ep-delete /></template>删除
									</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-row>
							<el-button type="primary" @click="handleZhichengAdd">添加证书</el-button>
						</el-row>

					</el-tab-pane>

					<el-tab-pane label="合同" name="hetong">
						<el-table :data="hetongData" style="width: 100%">
							<el-table-column label="签订日期" align="center" width="180">
								<template #default="scope">
									<el-date-picker v-model="scope.row.add_time" placeholder="请输入签订日期"
										value-format="YYYY-MM-DD" type="date" style="width:100%" />
								</template>
							</el-table-column>
							<el-table-column label="截止日期" align="center" width="180">
								<template #default="scope">
									<el-date-picker v-model="scope.row.end_time" placeholder="请输入截止日期"
										value-format="YYYY-MM-DD" type="date" style="width:100%" />
								</template>
							</el-table-column>
							<el-table-column label="有效期" align="center" width="200">
								<template #default="scope">
									<el-input v-model="scope.row.zhengshu" placeholder="请输入有效期" style="width:100%" />
								</template>
							</el-table-column>

							<el-table-column label="公司" align="center" width="250">
								<template #default="scope">
									<el-tree-select v-model="scope.row.company" placeholder="请选择所属公司"
										:data="baseConfigStore.newExCompanyList" filterable check-strictly
										:render-after-expand="false">
										<template v-slot:default="{node, data }">
											<treeBlock :nodeItem="node" :dataItem="data" :typeClass="0"></treeBlock>
										</template>
									</el-tree-select>
								</template>
							</el-table-column>

							<el-table-column label="法人" align="center" width="150">

								<template #default="scope">
									<el-input v-model="scope.row.legal_person" placeholder="请填写法人" style="width:100%" />
								</template>
							</el-table-column>

							<el-table-column label="试用期" align="center" width="150">
								<template #default="scope">
									<el-input v-model="scope.row.probation" placeholder="请填试用期" style="width:100%" />
								</template>
							</el-table-column>
							<el-table-column label="合同份数" align="center" width="150">
								<template #default="scope">
									<el-input-number v-model="scope.row.num" min="1" max="100" placeholder=""
										style="width:100%" />
								</template>
							</el-table-column>

							<el-table-column label="操作" fixed="right" align="center" width="150">
								<template #default="scope">
									<el-button type="danger" size="small" link
										@click="handleHetongDelete(scope.$index)">
										<template #icon><i-ep-delete /></template>删除
									</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-row>
							<el-button type="primary" @click="handleHetongAdd">添加合同</el-button>
						</el-row>

					</el-tab-pane>
				
					<el-tab-pane label="账号信息" name="account">
						
						<el-form-item label="账号信息" prop="userid">
							<el-input :disabled="formData.uid" v-model="formData.userid" placeholder="请输入初始账号信息" />
						</el-form-item>
						<el-form-item  v-if="formData.uid " label="重置密码" prop="pwd">
							<el-input type="password" placeholder="请输入重置密码" show-password v-model="formData.pwd" />
							<p style="color: #ff0000;">慎填，输入重置密码后将会修改当前密码！</p>
						</el-form-item>
						<el-form-item  v-else label="设置密码" prop="pwd">
							<el-input type="password" placeholder="请输入初始密码" show-password v-model="formData.pwd" />
						</el-form-item>
						
					</el-tab-pane>
				
				</el-tabs>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 导入弹框 -->
		<el-dialog v-model="importDialog.visible" :title="importDialog.title" width="600px" @close="closeImportDialog">
			<el-form label-width="80px">
				<el-form-item label="Excel">
					<el-upload class="upload-demo" action="" drag show-file-list :auto-upload="false"
						accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
						:on-change="handleExcelChange" :limit="1">
						<el-icon class="el-icon--upload">
							<i-ep-upload-filled />
						</el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>
						<template #tip>
							<div class="el-upload__tip">xls/xlsx files</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleUserImport">确 定</el-button>
					<el-button @click="closeImportDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>


<script setup lang="ts">
	defineOptions({
		name: "User",
		inheritAttrs: false,
	});
	import {
		getUserPage,
		getUserForm,
		addUser,
		updateUser,
		deleteUsers,
		exportUser,
		importUser,
		getBecomeDueList,
	} from "@/api/user";
	import { ElNotification } from 'element-plus'
	import { useTableFilterStore } from "@/store/modules/tableFilter";
	import { useBaseConfigStore } from "@/store/modules/baseConfig";
	import SingleUpload from "@/components/Upload/SingleUpload.vue";
	import { listRoleOptions } from "@/api/role";
	const baseConfigStore = useBaseConfigStore();
	const TableFilter = useTableFilterStore();
	const strtype = ref('user')
	// 表格标题
	const cTitles = ["ID","所属部门", "姓名", "职务名称","性别","联系方式","人员性质","工龄", "合同到期时间", "进入支部时间"];
	// 显示字段
	const sTitles = ["ID","所属部门", "姓名", "职务名称","性别","联系方式", "人员性质","工龄","合同到期时间"];
	// 字段属性	
	const cColumns = [
		{ label: "ID", prop: "uid", align: "center", width: 80 },
		{ label: "所属部门", prop: "department_name", align: "center", minwidth: 200 },
		{ label: "姓名", prop: "name", align: "center", width: 150 },
		{ label: "联系方式", prop: "mobile", align: "center", minwidth: 150 },
		{ label: "职务名称", prop: "position", align: "center", width: 130 },
		{ label: "性别", prop: "gender", align: "center", width:80 },
		{ label: "人员性质", prop: "type", align: "center", width: 120 },
		{ label: "工龄", prop: "seniority", align: "center", width: 100 },
		{ label: "合同到期时间", prop: "contract.status", align: "center", minwidth: 220 },
		{ label: "进入支部时间", prop: "entry_time", align: "center", minwidth: 220 },
	]
	interface TableGlobalLocal {
		[key : string] : any; // 或者更具体的类型
	}
	// 列表渲染
	function cColumnsList() {
		const ColumnsList = (TableFilter.tableGlobalLocal as TableGlobalLocal)[strtype.value + '_checklist'];
		if (ColumnsList) {
			const columnMap : any = {}; // 创建一个对象来存储cColumns中label和对象的映射  
			// 预先建立label到对象的映射  
			for (const column of cColumns) {
				columnMap[column.label] = column;
			}
			const newList = [];
			for (const label of ColumnsList) {
				// 尝试从映射中获取对象  
				const foundColumn = columnMap[label];
				if (foundColumn) {
					// 如果找到了，则添加到newList中  
					newList.push(foundColumn);
				}
			}
			return newList;
		}
		else {
			return [];
		}
	};
	// 列表-数据列初始化
	function columnsInit() {
		const dropColStr : string = strtype.value + '_dropCol';
		const checklistStr : string = strtype.value + '_checklist';
		const drop_col : any = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr];
		const checklist = (TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr];
		if (!drop_col) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[dropColStr] = JSON.parse(JSON.stringify(cTitles));
		}
		if (!checklist) {
			(TableFilter.tableGlobalLocal as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
			(TableFilter.tableGlobalLocalTemp as TableGlobalLocal)[checklistStr] = JSON.parse(JSON.stringify(sTitles));
		}
	}
	const dataTableRef =ref();
	const departmentRef = ref(ElTree);
	const rolesRef = ref(ElTree);
	const dataFormRef = ref(ElForm);
	const loading = ref(false);
	const loadingAdd = ref(false)
	const total = ref(0);
	const tableData = ref<any>([]);
	const roleOptions = ref();
	const multipleSelection =ref<any>([]);
	const menuLineVisible =ref(true);
	const rowR = ref<any>({});

	const showMore = ref(false);
	const queryParams = reactive<any>({
		page: 1,
		limit: 50,
		name: "", //姓名
		department: "", //部门
		roles: "",//角色
		type: "", //人员性质
		position: "", //职务
		gender: "", //性别
		// :"",//年龄
		seniority: "",//工龄
		work_time: "",//参加工作时间
		renming_time: "",//职务任命时间
		join_time: "",//入党时间
		xueli: "",//学历
		zhicheng: "",//职称
		zhengshu: "",//证书
		contract_date: "",//合同/劳务派遣/劳务外包（签订日期）
	});
	
	
	const dialogAdd = reactive<any>({
		title: "添加信息", //弹窗标题
		visible: false,   //弹窗显示or隐藏
		status: "add_art", //弹窗状态类型  :添加 add_art 编辑 edit_art 详情 detail_art  
		value: {}  
	});
	const importDialog = reactive<DialogOption>({
		visible: false,
		title: '批量导入'
	});

	const formData : any = reactive({
		uid: undefined,//信息id
		did: undefined,
		department: "", //部门
		roles: "",//角色
		name: "", //姓名
		position: "",//职务
		type: "",//人员性质
		gender: "",//性别
		mobile: "",//手机号
		idcard: "",//身份证号
		nation: "",//民族
		native_place: "",//籍贯
		birthday: "",//出生年月
		work_time: "",//参加工作时间
		renming_time: "",//职务任命时间
		join_time: "",//入党时间
		is_zhaogong: "",//是否有招工手续审批表
		political_landscape: "",//政治面貌
		mark: "",//备注信息
		avatar: "",//用户头像
		userid: "",//账号信息
		pwd: "",//密码
		seniority:"",//工龄
		// 最高学历
		qrzData: {
			id: undefined,
			uid: undefined,
			xueli: "", //学历
			school: "",//毕业学校
			zhuanye: "",//专业
			type: 1,
		},
		zgxlData: {
			id: undefined,
			uid: undefined,
			xueli: "",//最高学历
			school: "",//最高毕业院校
			zhuanye: "",//最高毕业专业
			type: 2,
		},
		isRestPsw:false,//是否重置密码
	});

	const zhichengData = ref<any>([]);
	const hetongData = ref<any>([]);
	const transferData = ref<any>([]);//人员调动

	const rules = reactive({
		department: [{ required: true, message: "请选择部门", trigger: "change" }],
		roles: [{ required: true, message: "请选择角色", trigger: "change" }],
		name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
		gender: [{ required: true, message: "请选择性别", trigger: "change" }],
		position: [{ required: true, message: "请输入职务", trigger: "blur" }],
		type: [{ required: true, message: "请选择人员性质", trigger: "change" }],
		mobile: [{ required: true, message: "请输入联系方式", trigger: "blur" }],
		userid: [{ required: true, message: "请输入初始账号", trigger: "blur" }],
		'qrzData.xueli': [{ required: true, message: "请选择学历", trigger: "change" }],
		'qrzData.school': [{ required: true, message: "请输入毕业院校", trigger: "blur" }],
		'qrzData.zhuanye': [{ required: true, message: "请输入专业", trigger: "blur" }],
		'zgxlData.xueli': [{ required: true, message: "请选择学历", trigger: "change" }],
		'zgxlData.school': [{ required: true, message: "请输入毕业院校", trigger: "blur" }],
		'zgxlData.zhuanye': [{ required: true, message: "请输入专业", trigger: "blur" }],
	});

	
	
	function filterMore() {
		showMore.value = !showMore.value
	}
	// 行菜单事件
	function rowMouse(row:any) {
		menuLineVisible.value = true
		rowR.value = row
	}
	// 数据多选事件
	function handleSelectionChange(val:any) {
		multipleSelection.value = val
	}
	// 操作按钮样式
	function buttonType(val:number) {
	 	if (val === 1) {
	 		return 'primary'
	 	} else {
	 		return 'info'
	 	}
	} 
	
	
	// 操作
	function handleDo(row:any, act:string) {
		
		switch (act) {
			case 'act_add':
				dialogAdd.visible = true;
				activeName.value = "user"
				dialogAdd.title = "新增人员";
				zhichengData.value = [];
				hetongData.value = [];
				transferData.value = [];
				
				nextTick(()=>{
					setTimeout(()=>{
						dataFormRef.value.clearValidate();
					},0)
				})
				
				break
			case 'act_edit':
				dialogAdd.visible = true;
				activeName.value = "user"
				dialogAdd.title = "修改人员信息";
				changeUserInfo(JSON.parse(JSON.stringify(row || multipleSelection.value[0])));
				break
			case 'act_del':
				handleDelete(JSON.parse(JSON.stringify(row || multipleSelection.value[0])))
				break
			default:	
		}
	}  
	function changeUserInfo(row:any){
		loadingAdd.value = true;
		getUserForm(row.uid).then(({ data }) => {
			Object.assign(formData, data);
			data.edu.forEach(function (item : any) {
				if (item.type == 1) {
					Object.assign(formData.qrzData, item);
				} else {
					Object.assign(formData.zgxlData, item);
				}
			});
			zhichengData.value = data.zhicheng;
			hetongData.value = data.contract;
			transferData.value = data.transfer;
			formData.isRestPsw = false;
			loadingAdd.value = false;
			
		});
	}
	
	/**
	 * 删除
	 */
	function handleDelete(row ?: any) {
		const Ids =row.uid;
		if (!Ids) {
			ElMessage.warning("请勾选删除项");
			return;
		}
		ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		}).then(() => {
			loading.value = true;
			deleteUsers(Ids)
				.then(() => {
					ElMessage.success("删除成功");
					resetQuery();
				})
				.finally(() => (loading.value = false));
		});
	}
	
	/**
	 * 查询
	 */
	function handleQuery() {
		loading.value = true;
		let searchModel : any = {};
		if (showMore.value) {
			searchModel = queryParams
		}
		else {
			searchModel.page = queryParams.page
			searchModel.limit = queryParams.limit
			searchModel.name = queryParams.name
			searchModel.department = queryParams.department
			searchModel.roles = queryParams.roles
		}
		getUserPage(queryParams)
			.then(({ data }) => {
				tableData.value = data.list;
				total.value = data.count;
			})
			.finally(() => {
				loading.value = false;
			});
	}
	/**
	 * 重置查询
	 */
	function resetQuery() {
		handleQuery();
	}

	
	/**
	 * 打开表单弹窗
	 *
	 * @param roleId
	 */
	function openDialog(Id ?: number) {
		dialogAdd.visible = true;
		activeName.value = "user"
		if (Id) {
			dialogAdd.title = "修改人员信息";
			getUserForm(Id).then(({ data }) => {
				Object.assign(formData, data);
				data.edu.forEach(function (item : any) {
					if (item.type == 1) {
						Object.assign(formData.qrzData, item);
					} else {
						Object.assign(formData.zgxlData, item);
					}
				});
				zhichengData.value = data.zhicheng;
				hetongData.value = data.contract;
				transferData.value = data.transfer
				// 回显账号所属部门
				const checkedDepartmentIds = data.department;
				if (checkedDepartmentIds) {
					setTimeout(function () {
						checkedDepartmentIds.forEach((Id) =>
							departmentRef.value.setChecked(Id, true, false)
						);
					}, 100);
				}
				// 回显账号所属角色
				const checkedRolesIds = data.roles;
				if (checkedRolesIds) {
					setTimeout(function () {
						checkedRolesIds.forEach((Id : any) =>
							rolesRef.value.setChecked(Id, true, false)
						);
					}, 100);
				}
			});
		} else {
			dialogAdd.title = "新增人员";
			zhichengData.value = []
			hetongData.value = []
			transferData.value = []
		}
	}

	/**
	 * 表单提交
	 */
	function handleSubmit() {
		loading.value = true;
		dataFormRef.value.validate((valid : any, message : any) => {
			console.log(message)
			if (valid) {
				const Id = formData.uid;
				formData.edu = [formData.qrzData, formData.zgxlData];
				formData.zhicheng = zhichengData.value;
				formData.contract = hetongData.value;
				formData.transfer = transferData.value;
				console.log(formData)
				if (Id) {
					updateUser(Id, formData)
						.then(() => {
							ElMessage.success("修改成功");
							closeDialog();
							resetQuery();
						})
						.finally(() => (loading.value = false));
				} else {
					addUser(formData)
						.then(() => {
							ElMessage.success("新增成功");
							closeDialog();
							resetQuery();
						})
						.finally(() => (loading.value = false));
				}
			}
			else {
				ElMessage.error("有必填信息未填写");
				loading.value = false;
			}
		});
	}

	/**
	 * 关闭弹窗
	 */
	function closeDialog() {
		dialogAdd.visible = false;
		resetForm();
	}

	/**
	 * 重置表单
	 */
	function resetForm() {
		dataFormRef.value.resetFields();
		dataFormRef.value.clearValidate();

		formData.did = undefined;
		formData.uid = undefined;
		formData.name = "";

	}

	
	/**
	 * 删除职称
	 * @param index 
	 */
	function handleZhichengDelete(index : number) {
		zhichengData.value.splice(index, 1);
	}
	/**
	 * 删除调动列表
	 * @param index 
	 */
	function handleTransferDataDelete(index : number) {
		transferData.value.splice(index, 1);
	}
	/**
	 * 添加职称
	 */
	function handleZhichengAdd() {
		zhichengData.value.push({
			jibie: "",
			zhuanye: "",
			zhengshu: "",
		})
	}
	/**
	 * 添加调动记录
	 */
	function handleTransferDataAdd() {
		transferData.value.push({
			type: "",
			date: "",
			place: "",
		})
	}
	/**
	 * 删除合同
	 * @param index 
	 */
	function handleHetongDelete(index : number) {
		// delete hetongData.value[index]
		hetongData.value.splice(index, 1);
	}
	/**
	 * 添加合同
	 */
	function handleHetongAdd() {
		hetongData.value.push({
			add_time: "",
			end_time: "",
			validity_time: "",
			company: undefined,
			legal_person: "",
			probation: "",
			num: undefined,
			is_zhaogong: 0,
		})
	}
	function onExport() {
		exportUser(queryParams).then((response : any) => {
			const blob = new Blob([response.data], {
				type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
			});
			const a = document.createElement("a");
			const href = window.URL.createObjectURL(blob); // 下载的链接
			a.href = href;
			a.download = decodeURI(
				response.headers["content-disposition"].split(";")[1].split("=")[1]
			); // 获取后台设置的文件名称
			document.body.appendChild(a);
			a.click(); // 点击导出
			document.body.removeChild(a); // 下载完成移除元素
			window.URL.revokeObjectURL(href); // 释放掉blob对象
		});
	}
	/**
	 * 下载导入模板
	 */
	function downloadTemplate() {
		const a = document.createElement("a");
		a.href = import.meta.env.VITE_APP_BASE_API + "/user.xlsx";
		a.download = "文件模板"
		document.body.appendChild(a);
		a.click(); // 点击下载
		document.body.removeChild(a); // 下载完成移除元素
	}
	const excelFile = ref<any>([]);
	/**
	 * 打开导入弹窗
	 */
	function openImportDialog() {
		importDialog.visible = true;
	}
	/**
	 * Excel文件change事件
	 *
	 * @param file
	 */
	function handleExcelChange(file : any) {
		if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
			ElMessage.warning("上传Excel只能为xlsx、xls格式");
			excelFile.value = undefined;
			return false;
		}
		excelFile.value = file.raw;
	}
	/**
	 * 表单提交
	 */
	function handleUserImport() {

		if (!excelFile.value) {
			ElMessage.warning("上传Excel文件不能为空");
			return false;
		}
		importUser(excelFile.value).then((response) => {
			ElMessage.success(response.data);
			closeImportDialog();
			resetQuery();
		});

	}

	/**
	 * 关闭导入弹窗
	 */
	function closeImportDialog() {
		importDialog.visible = false;
	}

	const activeName = ref('user')

	onUnmounted(() => {
		ElNotification.closeAll();
	})

	function retunTypeA(value : number) {
		const ArrC = [{ value: 1, title: '入职' },
		{ value: 2, title: '借入' },
		{ value: 3, title: '转岗' },
		{ value: 4, title: '借调' },
		{ value: 5, title: '离职' }]
		const downArr = ArrC.filter(item => item.value == value)
		if (downArr.length > 0) {
			return downArr[0].title
		}
		else {
			return '调动'
		}

	}

	onMounted(() => {
		handleQuery();
		columnsInit();

		listRoleOptions()
			.then(({ data }) => {
				roleOptions.value = data;
			})

		getBecomeDueList()
			.then(({ data }) => {
				console.log(data)

				if (data.jjgq.length > 0) {
					var html1 = "";
					for (var i = 0; i < data.jjgq.length; i++) {
						html1 += `<p>
										<span>${data.jjgq[i].name}</span>合同将于
										<span style="color:#ff0000">${data.jjgq[i].end_time}</span>
										到期
									</p>`
					}

					setTimeout(function () {
						ElNotification({
							title: '合同即将到期',
							dangerouslyUseHTMLString: true,
							message: html1,
							type: 'warning',
							duration: 0,
						})
					}, 0)
				}
				if (data.ygq.length > 0) {
					var html = "";
					for (var i = 0; i < data.ygq.length; i++) {
						html += `<p>
										<span>${data.ygq[i].name}</span>
										<span style="color:#ff0000">${data.ygq[i].end_time}</span>
										合同已到期
									</p>`
					}

					setTimeout(function () {
						ElNotification({
							title: '合同已到期提醒',
							dangerouslyUseHTMLString: true,
							message: html,
							type: 'error',
							duration: 0,
						})
					}, 300)


				}

			})
	});
</script>